package org.mtmi.io.controls;

import java.io.IOException;

import net.n3.nanoxml.IXMLElement;

import org.mtmi.io.ReaderError;
import org.mtmi.io.SceneReader;
import org.mtmi.io.SceneWriter;
import org.mtmi.io.XMLReader;
import org.mtmi.io.XMLWriter;
import org.mtmi.ui.controls.AbstractRangeValueControl;
import org.mtmi.ui.controls.Control;
import org.mtmi.ui.controls.ValueTransformer;
import org.mtmi.ui.controls.curve.CurveManager;
import org.mtmi.ui.controls.curve.CurveValueTransformer;

/**
 * In addition to {@link AbstractRangeValueControl}, save {@link ValueTransformer} features:
 * <ul>
 * <li> the index of curve used by value transformer (if any).
 * </ul>
 */
public class ValueTransformerIO extends RangeValueControlIO
{
	
	private static final String E_VT = "valueTransformer"; //$NON-NLS-1$
	private static final String A_CI = "curveIndex"; //$NON-NLS-1$

	public ValueTransformerIO() {
	}
	
	@Override
	public void writeControl( Control c, XMLWriter w, SceneWriter sw ) throws IOException 
	{
		super.writeControl(c, w, sw);
		
		//curve
		ValueTransformer vt = (ValueTransformer)c;
		if( vt.getValueTransformer() instanceof CurveValueTransformer ) {
			CurveValueTransformer cvt = (CurveValueTransformer)vt.getValueTransformer();
			int index = CurveManager.indexOf( cvt );			
			w.addElement( E_VT, A_CI, index ); 
		}
	}
	
	@Override
	public void readControl( Control c, IXMLElement element, XMLReader r, SceneReader sr ) throws ReaderError 
	{
		super.readControl(c, element, r, sr);
		
		//curve:
		IXMLElement e = r.getElement( element, E_VT, false );
		if( e!=null ) {
			int ci = r.getAttrInt( e, A_CI ); 

			ValueTransformer vt = (ValueTransformer)c;
			if( ci >= 0 ) {
				CurveValueTransformer cvt = CurveManager.getCurve( ci );
				vt.setValueTransformer( cvt );
			}
		}
	}
}
